let list = [
    { id: 1, name: '部门A', parentId: 0 },
    { id: 2, name: '部门B', parentId: 0 },
    { id: 3, name: '部门C', parentId: 1 },
    { id: 4, name: '部门D', parentId: 1 },
    { id: 5, name: '部门E', parentId: 2 },
    { id: 6, name: '部门F', parentId: 3 },
    { id: 7, name: '部门G', parentId: 2 },
    { id: 8, name: '部门H', parentId: 4 }
];

function list2tree(list) {
    const map = list.reduce((res, item) => {
        res[item.id] = item;
        return res;
    }, {});

    const res = [];

    for (let i = 0; i < list.length; i++) {
        if (list[i].parentId === 0) {
            res.push(map[list[i].id]);
            continue;
        }

        const parent = map[list[i].parentId];
        parent.children = parent.children || [];
        parent.children.push(list[i]);
    }

    return res;
}

console.log(JSON.stringify(list2tree(list)));

// [
//     { "id": 1, "name": "部门A", "parentId": 0, "children": [
//         { "id": 3, "name": "部门C", "parentId": 1, "children": [{ "id": 6, "name": "部门F", "parentId": 3 }] },
//         { "id": 4, "name": "部门D", "parentId": 1, "children": [{ "id": 8, "name": "部门H", "parentId": 4 }] }
//     ]}, 
//     { "id": 2, "name": "部门B", "parentId": 0, "children": [
//         { "id": 5, "name": "部门E", "parentId": 2 },
//         { "id": 7, "name": "部门G", "parentId": 2 }
//     ]}
// ]